import numpy as np
import csv
from datetime import datetime
from time import strftime


'''
Global and Local Empirical Bayes Smoothers with Gamma Model
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey



#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    print "begin at " + getCurTime()
    filepath = 'C:/_DATA/migration89_08/COUNTY Migration/clean/test/distinct_fips_Continental.csv'
    countyInfo = build_data_list(filepath)
    print len(countyInfo)

    fips_dic = {}
    for item in countyInfo:
        fips_dic[str(int(item[0]))] = int(item[1])

    filepath = 'C:/_DATA/migration89_08/COUNTY Migration/clean/test/shapefileAttri.csv'

    output = []
    data = build_data_list(filepath)
    '''
    for item in data:
        tempfips = ''
        tempcounty = str(int(item[1]))
        if len(tempcounty) < 2:
            tempfips = str(int(item[0])) + '00' + tempcounty
        elif len(tempcounty) < 3:
            tempfips = str(int(item[0])) + '0' + tempcounty
        else:
            tempfips = str(int(item[0])) + tempcounty

        if (tempfips in fips_dic.keys()):
            output.append(fips_dic[tempfips])
            output.append(tempfips)
            output.append(int(item[2]))
    '''

    for item in data:
        tempfips = str(int(item[1]))

        if (tempfips in fips_dic.keys()):
            output.append(int(item[0]))
            output.append(int(fips_dic[tempfips]))
        else:
            output.append(int(item[0]))
            output.append(-1)
            
    output = np.array(output)
    output.shape = (-1, 2)
    print output

    #tempList = [0,10,42,25,23,50,18,52,3,61,58,43,65,6,32,5,20,54,60]
    #sum = 0
    #for i in tempList:
        #sum += int(output[i, 2])
    #print sum
    np.savetxt(filepath[:-4] + '_id.csv', output, delimiter=',', fmt = '%i')
